package com.yipai.datewidget.booking.page;

import static org.jaaksi.pickerview.picker.TimePicker.DEFAULT_TIME_FORMAT;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import com.yipai.datewidget.booking.BookingSharedViewModel;
import com.yipai.datewidget.booking.R;
import com.yipai.datewidget.booking.base.BaseFragment;
import com.yipai.datewidget.booking.config.Config;
import com.yipai.datewidget.booking.databinding.FragmentTimePickerBinding;
import com.yipai.datewidget.booking.utils.PixUtils;

import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.TimePicker;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class TimePickerFragment extends BaseFragment {

    public static TimePickerFragment newInstance(int index) {
        Bundle args = new Bundle();
        TimePickerFragment fragment = new TimePickerFragment();
        args.putInt(Config.KEY_INDEX, index);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 1980-01-01 0:0:0
     */
    public static final long START_DATE = 315504000000L;
    /**
     * 2080-01-01 24:0:0
     */
    public static final long END_DATE = 3471350400000L;
    /**
     * 1980-01-01 08:30:00
     */
    public static final long DEFAULT_DATE = 315534600000L;
    /**
     * 最大可见行数
     */
    public static final int VISIBLE_ITEM_COUNT = 6;
    public static final int TIME_MINUTE_START = 0;
    public static final int TIME_MINUTE_OFFSET = 30;

    private TimePicker mStartTimePicker;
    private TimePicker mEndTimePicker;
    private FragmentTimePickerBinding mFragmentTimePickerBinding;
    private int mPageIndex;
    private BookingSharedViewModel mBookingSharedViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentTimePickerBinding = FragmentTimePickerBinding.inflate(inflater, container, true);
        // 时间控件样式配置
        DefaultCenterDecoration.sDefaultLineColor = 0xffEBEDF0;
        PickerView.sOutTextSize = PixUtils.sp2dp(getContext(), 15);
        PickerView.sCenterTextSize = PixUtils.sp2dp(getContext(), 20);
        PickerView.sCenterColor = 0xff323233;
        PickerView.sOutColor = 0xff646566;
        initData();
        initUI();
        initObserver();
        return mFragmentTimePickerBinding.getRoot();
    }

    private void initObserver() {
        mBookingSharedViewModel.mStartTimeMutableLiveData.observe(getViewLifecycleOwner(), new Observer<Date>() {
            @Override
            public void onChanged(Date date) {
                if(date != null){
                    mStartTimePicker.setSelectedDate(date.getTime());
                }
            }
        });
        mBookingSharedViewModel.mEndTimeMutableLiveData.observe(getViewLifecycleOwner(), new Observer<Date>() {
            @Override
            public void onChanged(Date date) {
                if(date != null){
                    mEndTimePicker.setSelectedDate(date.getTime());
                }
            }
        });
    }

    private void initUI() {
        addPickerView(mStartTimePicker.view());
        addPickerView(mEndTimePicker.view());

        mFragmentTimePickerBinding.tvNextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String startTime = DEFAULT_TIME_FORMAT.format(mStartTimePicker.getSelectedDates());
                String endTime = DEFAULT_TIME_FORMAT.format(mEndTimePicker.getSelectedDates());
                if (endTime.compareTo(startTime) <= 0) {
                    Toast.makeText(getContext(), R.string.time_picker_range_error_tips, Toast.LENGTH_SHORT).show();
                    return;
                }

                setValue();
                mBookingSharedViewModel.mNextStepUnPeekLiveData.setValue(mPageIndex);
            }
        });
    }

    private void initData() {
        mBookingSharedViewModel = getActivityScopeViewModel(BookingSharedViewModel.class);
        mPageIndex = getArguments().getInt(Config.KEY_INDEX);

        Date date = new Date();
        mStartTimePicker = createTimePicker(date, true);
        mEndTimePicker = createTimePicker(date, false);
    }

    private void addPickerView(View pickerView){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.weight = 1;
        mFragmentTimePickerBinding.llContainer.addView(pickerView, layoutParams);
    }

    private TimePicker createTimePicker(Date date, boolean isStart){
        return new TimePicker.Builder(getContext(), TimePicker.TYPE_HOUR | TimePicker.TYPE_MINUTE, null)
                .setRangDate(START_DATE, END_DATE)
                .setSelectedDate(getDefaultSelectedDate(date, isStart))
                .setFormatter(new TimePicker.DefaultFormatter() {
                    @Override
                    public CharSequence format(TimePicker picker, int type, int position, long value) {
                        if(type == TimePicker.TYPE_MINUTE || type == TimePicker.TYPE_HOUR){
                            return String.format(Locale.getDefault(), "%02d",value);
                        }
                        return super.format(picker, type, position, value);
                    }
                })
                .dialog(null)
                .setTimeMinuteOffset(TIME_MINUTE_OFFSET)
                // 设置pickerview样式
                .setInterceptor(new BasePicker.Interceptor() {
                    @Override
                    public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                        pickerView.setVisibleItemCount(VISIBLE_ITEM_COUNT);
                    }
                }).create();
    }

    private void setValue(){
        mBookingSharedViewModel.mStartTimeMutableLiveData.setValue(mStartTimePicker.getSelectedDates());
        mBookingSharedViewModel.mEndTimeMutableLiveData.setValue(mEndTimePicker.getSelectedDates());
    }

    @Override
    public void onEvent() {
        super.onEvent();

        setValue();
    }

    private long getDefaultSelectedDate(Date date, boolean isStart){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);


        if(minute < TIME_MINUTE_OFFSET){
            calendar.set(Calendar.MINUTE, TIME_MINUTE_OFFSET);
        } else {
            // 当前大于30分钟 直接更新到下一时的0分
            calendar.set(Calendar.MINUTE, TIME_MINUTE_START);
            calendar.set(Calendar.HOUR_OF_DAY, hour + 1);
        }

        // 如果是结束时间，还得加30分钟
        if(!isStart){
            int endMin = calendar.get(Calendar.MINUTE) + TIME_MINUTE_OFFSET;
            calendar.set(Calendar.MINUTE, endMin);
        }

        return calendar.getTimeInMillis();
    }
}
